package com.by.interceptor;

import org.springframework.util.Base64Utils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

public class AuthInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求头 auth
        String auth=request.getHeader("Authorization");
        response.setContentType("text/plain;charset=utf-8");
        if(null==auth){
            //提示
            response.getWriter().write("无取访问！");
            return  false;
        }

        //得到的值 Basic laskdflaldsflk
        String []tmp=auth.split("\\s+");
        String enstr=tmp[1];//这是加密后的字符串
        //解密
        String userpwd=new String(Base64Utils.decode(enstr.getBytes()));
        tmp=userpwd.split(":");
        String username=tmp[0];
        String password=tmp[1];
        if("admin".equals(username)&&"1357".equals(password)){
            System.out.println("yonghuxx验证通过zpf");
            return true;//放行
        }else{
            //授权信息错误
            response.getWriter().write("账号信息错误");
            return false;
        }

    }

}
